﻿namespace EyeOpen.Webcam.Silverlight
{
	using System;
	using System.IO;
	using System.Windows;
	using System.Windows.Media;
	using System.Windows.Media.Imaging;

	public partial class MainPage
	{
		private const string Host = "localhost:6691";

		private CaptureSource captureSource;
		private int frameCount;

		public MainPage()
		{
			InitializeComponent();
		}

		private void EnableWebcam(object sender, RoutedEventArgs e)
		{
			if (captureSource != null)
			{
				return;
			}

			captureSource =
				new CaptureSource
				{
					VideoCaptureDevice = 
						CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice()
				};

			display.SetSource(captureSource);
			displayRotated.SetSource(captureSource);

			CaptureDeviceConfiguration.RequestDeviceAccess();

			if (
				!CaptureDeviceConfiguration.AllowedDeviceAccess && 
				!CaptureDeviceConfiguration.RequestDeviceAccess())
			{
				return;
			}

			this.captureSource.Start();

			captureSource.CaptureImageCompleted += CaptureCaptureImageCompleted;
			captureSource.CaptureImageAsync();
		}
		
		private void CaptureCaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
		{
			if (frameCount <= 30)
			{
				frameCount++;
				((CaptureSource)sender).CaptureImageAsync();
				return;
			}

			frameCount = 0;

			using (var stream = new MemoryStream())
			{
				var writeableBitmap = e.Result;

				writeableBitmap
					////.Resize(60, 44, WriteableBitmapExtensions.Interpolation.Bilinear)
					.WriteTga(stream);

				var buffer = stream.ToArray();

				var streamService =
					this
						.CreateService<IStreamServiceAsync>(string.Format("http://{0}/StreamService", Host));
				
				Dispatcher
					.BeginInvoke(
						() => 
							streamService
								.BeginCapture(
									buffer,		
									DateTime.Now,
									streamService.EndCapture, 
									streamService));
			}

			((CaptureSource)sender).CaptureImageAsync();
		}
	}
}